package com.qire.manhua.dal.service;

import com.qire.antsbinder.dal.DataService;
import com.qire.common.collect.ListUtil;
import com.qire.common.concurrent.Scheduler;
import com.qire.common.concurrent.ThreadUtil;
import com.qire.common.utils.FileManager;
import com.qire.manhua.dal.dao.ComicChapterDao;
import com.qire.manhua.dal.dao.ComicChapterDao.ComicId;
import com.qire.manhua.dal.dao.ComicDatabase;
import com.qire.manhua.dal.dao.ComicDownloadDao;
import com.qire.manhua.model.po.ComicDownloadRecord;
import com.qire.manhua.model.po.LocalComicChapter;
import com.qire.manhua.model.viewModel.impl.BookshelfDownloadViewModel;
import com.qire.manhua.model.viewModel.impl.BookshelfDownloadViewModel.DownloadItemViewModel;

import java.util.List;

/**
 * 首页书架下载页面数据服务
 */
public class HomeBookshelfDownloadService extends DataService {

    private final ComicDownloadDao comicDownloadDao = ComicDatabase.database().comicDownloadDao();
    private final ComicChapterDao comicChapterDao = ComicDatabase.database().comicChapterDao();

    private final BookshelfDownloadViewModel viewModel;

    public HomeBookshelfDownloadService(BookshelfDownloadViewModel viewModel) {
        this.viewModel = viewModel;
    }

    public void loadLocalDownloadData() {
        ThreadUtil.once().andThen(data -> {
            List<ComicDownloadRecord> downloadRecordList = comicDownloadDao.queryAll();
            viewModel.clearDownloadList();
            for(ComicDownloadRecord record : downloadRecordList) {
                List<LocalComicChapter> comicChapterList = comicChapterDao.queryListBy(record.getId());
                if(ListUtil.isEmpty(comicChapterList)) {
                    comicDownloadDao.delete(record);
                } else {
                    DownloadItemViewModel itemViewModel = viewModel.buildDownloadItemViewModel(record.getId(), record.getComicName(), record.getCover());
                    itemViewModel.resetChapterWrapper();
                    for(LocalComicChapter comicChapter : comicChapterList) {
                        itemViewModel.addChapterWrapper(comicChapter.getId(), comicChapter.getDownloadState());
                    }
                    viewModel.addDownloadItemViewModel(itemViewModel);
                }
            }
        }).schedulerBy(Scheduler.Main).andThen(data -> {
            viewModel.refreshUI();
        }).accept();
    }

    /**
     * 批量删除文件及数据库
     * @param comicIdArray
     */
    public void batchDeleteDownloadRecord(final Integer[] comicIdArray) {
        ThreadUtil.start(() -> {
            for(int comicId : comicIdArray) {
                comicChapterDao.deleteByComic(new ComicId(comicId));
                FileManager.deleteComicFolder(comicId);
            }
            // 重新加载下载漫画数据列表，在这里，如果下载记录中数据对于的下载章节目录为空则自动删除这条记录已达到删除下载记录数据库的目的
            loadLocalDownloadData();
        });
    }

}
